<script lang="ts" setup>
import http from '@/http';
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { useCookies } from '@vueuse/integrations/useCookies'
import { useUserStore } from '@/stores/user';


const cookies = useCookies()

const suerStrore = useUserStore()
const router = useRouter()

//和表单数据双向绑定的对象
const ruleForm = reactive({
  uname: '',//用户名
  pwd: '',//密码
})

// 处理登录逻辑
const handleLogin = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  //请求验证成功
  console.log('请求成功!')
  // 向后端发送请求
  http.post('/user/checkLogin', ruleForm)
    .then((res => {
      if (res != "") {
        //登录成功
        //弹出成功提示信息
        ElMessage({
          message: '登录成功',
          type: 'success',
        })
        //判断是否存在token
        // if(cookies.get(suerStrore.getUser)){
        //   //删除token
        //   cookies.remove("token")
        // }
        //跳转到主页面
        cookies.set('token', res)
        router.push('/index')
      } else {
        //登录失败,弹出失败提示信息
        ElMessage({
          message: '登录失败',
          type: 'error',
        })
      }
    }))
}
</script>

<template>
  <div id="app">
    <div class="login-container">
      <h1>登录</h1>
      <form>
        <div class="form-group">
          <label for="ruleForm">用户名:</label>
          <input type="text" id="username" v-model="ruleForm.uname" placeholder="请输入用户名" required />
        </div>
        <div class="form-group">
          <label for="password">密码:</label>
          <input type="password" id="password" v-model="ruleForm.pwd" placeholder="请输入密码" required />
        </div>
        <button  type="button" @click="handleLogin(ruleForm)">登录</button>
      </form>
    </div>
  </div>
</template>
<style scoped>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

.login-container {
  width: 300px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 15px;
  text-align: left;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
}

.form-group input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 3px;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}
</style>